﻿using System.ComponentModel;
using System.Reflection;
using BPanel.Core.Extensions.Models;

namespace BPanel.Core.Extensions;

public static class EnumExtension
{
    public static Dictionary<string, int> ToDictionary(this Type enumType)
    {
        var enumValues = Enum.GetValues(enumType);

        var dictionary = new Dictionary<string, int>();

        foreach (var value in enumValues)
        {
            var name = Enum.GetName(enumType, value);
            var val = (int)value;

            dictionary.Add(name ?? throw new Exception("Enum Name Value Is Not Found"), val);
        }

        return dictionary;
    }

    public static List<KeyValueModel> ToList(this Type enumType)
    {
        var enumValues = Enum.GetValues(enumType);

        var list = new List<KeyValueModel>();

        foreach (var value in enumValues)
        {
            var name = Enum.GetName(enumType, value);
            var val = (int)value;

            list.Add(new KeyValueModel
            {
                Key = name ?? throw new Exception("Enum Name Value Is Not Found"),
                Value = val
            });
        }

        return list;
    }


    public static List<KeyValueModel> ToDescriptionList(this Type enumType)
    {
        var list = new List<KeyValueModel>();
        // 获取枚举的所有成员
        var fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);

        foreach (FieldInfo field in fields)
        {
            // 获取DescriptionAttribute
            var descriptionAttribute = field.GetCustomAttribute<DescriptionAttribute>();
            if (descriptionAttribute != null)
            {
                // 获取枚举值
                var enumValue = (int)field.GetValue(null)!;
                // 获取描述
                var description = descriptionAttribute.Description;

                list.Add(new KeyValueModel()
                {
                    Key = description,
                    Value = enumValue
                });
            }
        }

        return list;
    }
}